<!DOCTYPE html>
<html>
<head>
    <title>简单的聊天工具</title>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/angular.js/1.4.6/angular.min.js"></script>
</head>
<script type="text/javascript">

    var websocket = null;
    if ('WebSocket' in window) {
        websocket = new WebSocket('ws://localhost:9000/webSocket');
    } else {
        alert('该浏览器不支持websocket');
    }
    websocket.onopen = function (ev) {
        console.log('建立连接');
    };
    websocket.onclose = function (ev) {
        console.log('连接关闭');
    };
    websocket.onmessage = function (ev) {
        console.log('收到消息：' + ev.data);
        var date = new Date();
        date = date.Format("yyyy年MM月dd hh:mm:ss");
        $('#msgdiv').prepend('<h3 style="color: #0c141f;margin: -8px 0px -2px -11px">' + ev.data + '</h3>');
        $('#msgdiv').prepend('<p style="font-size: 12px;color: #596363;">' + date + '</p>')
    };
    window.onbeforeunload = function (ev) {
        websocket.close();
    };

    function sendMsg() {
        var msgNode = document.getElementById("msg");
        var msg = msgNode.value;
        if (msg) {
            websocket.send(msg);
        }
        msgNode.value = '';
    }

    function setName() {
        var nameNode = document.getElementById("name");
        var name = nameNode.value;
        websocket.send(name + "::");
        nameNode.value = '';
    }
    $(function (e) {
        $('#msg').keydown(function (event) {
            if (event.keyCode == 13) {
                sendMsg();
            }
        });
    });
</script>
<body>
<h1>简单的聊天</h1>
<button onclick="setName()">设置昵称</button>
<input type="text" id="name" name="name" />
<hr />
<button onclick="sendMsg()">发送消息</button>
<textarea type="text" id="msg" name="msg"></textarea>
<hr />
<div ng-app="" id="msgdiv"></div>
</body>
<script>
    Date.prototype.Format = function (fmt) { //author: meizz
        var o = {
            "M+": this.getMonth() + 1, //月份
            "d+": this.getDate(), //日
            "h+": this.getHours(), //小时
            "m+": this.getMinutes(), //分
            "s+": this.getSeconds(), //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
</script>
</html>
